using System;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace ImportDataToDataBaseExtensionPlugin.Common
{
    public static class GetDataFromExcel
    {
        public static DataTable ExcelToDatatable(string fileName, string sheetName = null, bool isFirstRowColumn = true)
        {
            var data = new DataTable();
            
            var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            IWorkbook workbook = null;
            if (fileName.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本
            {
                workbook = new XSSFWorkbook(fs);
            }
            else if (fileName.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本
            {
                workbook = new HSSFWorkbook(fs);
            }
            else
            {
                return null;
            }

            ISheet sheet = null;
            sheet = sheetName != null ? 
                workbook.GetSheet(sheetName) : 
                workbook.GetSheetAt(0); //获取第几个sheet表（此处表示如果没有给定sheet名称，默认是第一个sheet表）  
            
            if (sheet == null) return data;
            var firstRow = sheet.GetRow(0);
            int cellCount = firstRow.LastCellNum;//列数
            var startRow = 0;
            if (isFirstRowColumn)//如果第一行是标题行
            {
                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)//第一行列数循环
                {
                    var column = new DataColumn(firstRow.GetCell(i).StringCellValue);//获取标题
                    data.Columns.Add(column);//添加列
                }
                startRow = sheet.FirstRowNum + 1;//1（即第二行，第一行0从开始）
            }
            else
            {
                startRow = sheet.FirstRowNum;//0
            }
            //最后一行的标号
            var rowCount = sheet.LastRowNum;//行数
            for (var i = startRow; i <= rowCount; ++i)//循环遍历所有行
            {
                var row = sheet.GetRow(i);//第几行
                if (row == null)
                {
                    continue; //没有数据的行默认是null;
                }
                //将excel表每一行的数据添加到datatable的行中
                var dataRow = data.NewRow();
                for (int j = row.FirstCellNum; j < cellCount; ++j)
                {
                    if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                    {
                        dataRow[j] = row.GetCell(j).ToString() ?? string.Empty;
                    }
                }
                data.Rows.Add(dataRow);
            }
            return data;
            
        }
    }
}